package com.dotndot.momserver.servlet;

import java.io.*;

import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.images.*;

@SuppressWarnings( "serial" )
public class BasicServlet extends HttpServlet
{

    public enum MULTIPART_TYPE
    {
        BABY_TYPE,

    }

    private void getBabyFormField( FileItemStream item, InputStream istream )
    {
        if( item.getFieldName().equals("subject") )
        {
            // userInfo.setIntroduction(Streams.asString(istream));
        }
    }

    private void getFormField( MULTIPART_TYPE type, FileItemStream item, InputStream istream )
    {
        switch( type )
        {
            case BABY_TYPE:

                break;
        }
    }

    /** Network Utils **/
    public Object multipartParam( MULTIPART_TYPE type, HttpServletRequest req )
    {

        try
        {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(req);
            while( iterator.hasNext() )
            {
                FileItemStream item = iterator.next();
                InputStream istream = item.openStream();
                if( item.isFormField() )
                {

                    if( item.getFieldName().equals("subject") )
                    {
                        // userInfo.setIntroduction(Streams.asString(istream));
                    }
                }
                else
                {
                    int len;
                    byte[] buffer = new byte[8192];
                    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
                    while( (len = istream.read(buffer, 0, buffer.length)) != -1 )
                    {
                        oStream.write(buffer, 0, len);
                    }

                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image oldImage = ImagesServiceFactory.makeImage(oStream.toByteArray());
                    Transform resize = ImagesServiceFactory.makeResize(100, 200);
                    Image newImage = imagesService.applyTransform(resize, oldImage);

                    byte[] newImageData = newImage.getImageData();
                    Blob photofile = new Blob(newImageData);
                    // userInfo.setAvatar(photofile);

                    // resp.setContentType("text/xml");
                    // resp.getWriter().println(XML.commonXML(E001));

                }
            }

        }
        catch( Exception e )
        {

        }
        return req;
    }
}
